<template>
  <div class="roleManner">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span><el-button type="primary" size="small" @click="addRole">新增角色</el-button>
        </span>
      </div>
      <el-table
        v-loading="loading"
        :data="roleList"
        :fit="true"
        :header-cell-style="{background:'#FAFAFA'}"
        style="width: 90%"
      >
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="50"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="name"
          label="角色名称"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="describe"
          label="角色描述"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="goodStatus"
          label="操作"
          width="200"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="detail(scope.row.id)">查看用户</el-button>
            <el-button type="text" size="small" @click="setAuth(scope.row)">设置权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pages"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.start"
        :page-sizes="page.size"
        :page-size="page.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      ></el-pagination>
    </el-card>
    <el-dialog
      class="roleDialog"
      v-loading="menuLoading"
      title="设置角色"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
            <el-form :model="roleObj" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <div class="box">
                  <el-form-item label="基本信息:" prop="name">
                    <el-input v-model.trim="roleObj.name" clearable class="ipt" maxlength="20" placeholder="请输入角色名称" size="small" ></el-input>
                  </el-form-item>
              </div>
              <div class="box">
                <el-form-item label="角色描述:" prop="describe">
                  <el-input v-model.trim="roleObj.describe" type="textarea" maxlength="100" resize="none" :rows="5" class="ipt" placeholder="请输入角色描述" size="small" ></el-input>
                </el-form-item>
              </div>
            </el-form>
        </el-tab-pane>
        <el-tab-pane label="角色设置" name="second">
          <el-tree
            :data="routeList"
            ref="menuTree"
            @check="select"
            show-checkbox
            node-key="id"
            :default-expanded-keys="checkedMenu"
            :default-checked-keys="checkedMenu"
            :props="defaultProps">
          </el-tree>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" :loading="submiting" @click="doSubmit('ruleForm')">提 交</el-button>
        <el-button size="small" @click="cancle('ruleForm')">取 消</el-button>
      </span>
    </el-dialog>
    <Dialogs :vilable= visible v-if="isShow" :showGroup= true :roleId= id @childClose= parentClose></Dialogs>
  </div>
</template>

<script>
import systemApi from "@/api/lejv/system"
import Dialogs from "@/layout/components/Dialogs"
import asyncRouter from "@/router/asyncRouter"
import _ from "lodash"; //引入lodash
export default {
  name: "roleManner",
  components:{
    Dialogs
  },
  data() {
    return {
      id: -1,
      isShow:false,
      submiting:false,
      loading:false,
      menuLoading:false,
      isAdd:false,
      editId:"",
      dialogVisible: false,
      visible: false,
      activeName: 'first',
      roleObj:{
        name:"",
        describe:""
      },
      rules: {
          name: [
            { required: true, message: '请输入角色名称', trigger: 'blur' }
          ],
      },
      roleList:[],
      page: { //分页
        start: 1,
        limit: 10,
        total: 10,
        size: [10, 20, 30],
      },
      //角色菜单
      data: [
        // {
        //   id: 1,
        //   label: '一级 1',
        //   children: [{
        //     id: 4,
        //     // level:1,
        //     label: '二级 1-1',
        //   }]
        // }, {
        //   id: 2,
        //   label: '一级 2',
        //   children: [{
        //     id: 5,
        //     // level:2,
        //     label: '二级 2-1'
        //   }, {
        //     id: 6,
        //     // level:2,
        //     label: '二级 2-2'
        //   }]
        // }, {
        //   id: 3,
        //   label: '一级 3',
        //   children: [{
        //     id: 7,
        //     // level:3,
        //     label: '二级 3-1'
        //   }, {
        //     id: 8,
        //     // level:3,
        //     label: '二级 3-2'
        //   }]
        // }
      ],
      checkMenu:[],//选中的菜单
      doneMenu:[],//提交得菜单
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    };
  },
  computed: {
    routeList(){
      let arr = []
      return asyncRouter.reduce((a,b)=>{
        // console.log(b.name);
        if(b.path == "/"){
          arr.push({ id: 1001,label:"首页概览",})
        }else{
          let obj = {
            id: b.node_id,
            label: b.meta.title,
          }
          if(b.children){
            obj.children = b.children.map(item =>{
              if(!item.hidden){
                return {
                  id: item.node_id,
                  label: item.meta.title
                }
              }
            })
            obj.children = obj.children.filter(item => item)
          }
          if(obj.id != 1501){  //系统设置不在权限列表内
            arr.push(obj)
            // console.log(arr)
          }
          return arr
        }
      },[])
    },
    checkedMenu(){
      return this.checkMenu
    }
  },
  created() { 
    // console.log(asyncRouter);
    this.page.total = this.roleList.length
    this.getRoleList()
  },
  mounted() {},
  methods: {
    //获取角色列表
    getRoleList(){
      let params = {
        pageSize: this.page.limit,
        pageNum: this.page.start
      }
      this.loading = true
      systemApi.getRoleList(params)
      .then(res=>{
        // console.log(res);
        if(res.code == 0){
          this.loading = false
          this.roleList = res.data.roles
          this.page.total = res.data.totalElements
          let item  = res.data.roles.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
          if(this.$store.state.app.roleList.length == 0){
            this.$store.state.app.roleList = item
          }
        }
      })
      .catch(res=>{
        this.loading = false
        // this.$message({
        //   type:"error",
        //   message:"获取角色列表失败"
        // })
      })
    },
    //新增角色
    addRole(){
      this.dialogVisible = true
      this.isAdd = true
    },
    //编辑
    edit(val){
      this.activeName = 'first'
      this.dialogVisible = true
      this.getRoleMenu(val)
    },
    //查看用户
    detail(id){
      this.isShow = true
      this.visible = true
      this.id = id
    },
    //设置权限
    setAuth(val){
      this.activeName = 'second'
      this.getRoleMenu(val)
    },
    //获取权限列表详情
    getRoleMenu(val){
      this.isAdd = false
      this.dialogVisible = true
      this.menuLoading = true
      this.editId = val.id
      this.roleObj = {...val}
      delete this.roleObj.id
      systemApi.getMenuList({roleId:val.id})
      .then(res=>{
        // console.log(res);
        if(res.code == 0){
          let item = res.data.menus
          if(item.length == 0){
            this.checkMenu = []
            this.doneMenu = []
          }else{
            for(let i = 0;i<item.length;i++){
              if(item[i].children.length == 0){
                // this.checkMenu.push(item[i].node_id)
                this.doneMenu.push(item[i].node_id)
              }else{
                // this.doneMenu.push(item[i].node_id)
                for(let j = 0 ;j<item[i].children.length;j++){
                  // this.checkMenu.push(item[i].children[j].node_id)
                  this.doneMenu.push(item[i].children[j].node_id)
                }
              }
            }
          }
          // console.log(this.doneMenu);
          this.$nextTick(()=>{
            this.checkMenu = [...this.doneMenu]
          })
        }else{
          this.$message({
            type:"warning",
            message: res.msg
          })
        }
        this.menuLoading = false
        // this.dialogVisible = true
      })
      .catch(res=>{
        this.menuLoading = false
        // this.$message({
        //   type:"error",
        //   message: "获取权限列表失败"
        // })
      })
    },

    //选择菜单权限
    select(val,item){
      let arr = item.checkedKeys.concat(item.halfCheckedKeys)
      this.doneMenu = arr
      // console.log(val,this.$refs.menuTree.getCheckedNodes(),this.$refs.menuTree.getHalfCheckedNodes());
    },
    //组件选择产品弹窗
    parentClose(){
      this.isShow = !this.isShow
      this.visible = !this.visible
    },
    //关闭弹窗
    handleClose(done) {
      this.checkMenu = []
      this.doneMenu = []
      this.activeName = 'first'
      this.$refs.ruleForm.resetFields()
      this.roleObj = this.$options.data().roleObj
      this.$refs.menuTree.setCheckedNodes(this.$options.data().checkMenu)
      done()
    },
    //弹窗提交
    doSubmit(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.doneMenu.length == 0){
            this.$message({
              type:"warning",
              message:"请选择菜单列表"
            })
            this.activeName = 'second';
          }else{
            let count = 0;
            this.submiting = true;
            let api = null,menuObj = {id:'',menuIdList:''},params = {...this.roleObj};
            if(this.isAdd){
              api = systemApi.addRole //新增角色
            }else{
              api = systemApi.updateRole //修改角色
              params.id = this.editId
            }
            // console.log(this.doneMenu,this.$refs.menuTree.getCheckedKeys(),this.$refs.menuTree.getHalfCheckedKeys());
            let newArr = this.$refs.menuTree.getCheckedKeys().concat(this.$refs.menuTree.getHalfCheckedKeys())
            this.doneMenu = newArr
            api(params)
            .then(res=>{
              // console.log(res);
              if(res.code == 0){
                if(res.data){
                  menuObj.id = res.data
                }else{
                  menuObj.id = this.editId
                }
                menuObj.menuIdList = this.doneMenu.join(",")
                count++
                systemApi.updateRoleMenu(menuObj) // 新增角色的弹窗 后台设置两个接口 所以菜单的新增和修改只有一个接口
                .then(res=>{
                  if(res.code == 0){
                    count++
                    if(count == 2){ //确保两个接口都提交成功
                      this.submiting = false
                      this.cancle(formName)
                      this.$message({
                        type:'success',
                        message:'权限设置成功'
                      })
                      this.getRoleList()
                    }
                  }else{
                    this.$message({
                      type:'warning',
                      message: res.msg
                    })
                    this.submiting = false
                  }
                })
                .catch(res=>{
                  count = 0
                  // console.log("第二");
                  this.$message({
                    type:'error',
                    message:'权限设置失败'
                  })
                  this.submiting = false
                })
              }else{
                this.submiting = false
                this.$message({
                  type:"warning",
                  message: res.msg
                })
              }
            })
            .catch(res=>{
              // console.log("第一");
              count = 0
              this.$message({
                type:'error',
                message:'权限设置失败'
              })
              this.submiting = false
            })
          }
        } else {
          this.activeName = 'first';
          return false;
        }
      });
    },
    //弹窗取消
    cancle(formName){
      this.checkMenu = []
      this.doneMenu = []
      this.$refs.menuTree.setCheckedNodes(this.$options.data().checkMenu)
      this.isAdd = false;
      this.activeName = 'first';
      this.$refs.ruleForm.resetFields();
      this.roleObj = this.$options.data().roleObj //确保关闭后清空
      this.dialogVisible = false
    },
    //分页切换
    handleSizeChange(val) {
      this.page.limit = val;
      this.getRoleList();
    },
    //分页
    handleCurrentChange(val) {
      this.page.start = val;
      this.getRoleList();
    },
    //路由转换菜单(弃用)
    routeMenu(){
      let routeList = []
      for(let i = 0;i<asyncRouter.length;i++){
        // let obj = {};
        if(i == 0){
          routeList.push({ id: 1,label:"首页概览",})
        }else{
          if(asyncRouter[i].children){
            let obj = {
              id: i+1,
              label: asyncRouter[i].meta.title,
              children:[]
            }
            for(let j = 0;j<asyncRouter[i].children.length;j++){
              if(!asyncRouter[i].children[j].hidden){
                let childObj = {
                  id: j + 1 + "a",
                  label: asyncRouter[i].children[j].meta.title
                }
                obj.children.push(childObj)
              }
            }
            routeList.push(obj)
          }
        }
      }

      // console.log(asyncRouter,this.routeList,);
      this.data = this.routeList
    }
  }
};
</script>
<style lang="scss" >
body{
  padding-right: 0px !important;
  // overflow: overlay;
}
</style>
<style scoped lang="scss">
::v-deep.roleManner {
  margin: 20px;
  .roleDialog{
    .el-dialog__header{
      border-bottom: 1px solid #E0E0E0;
    }
    .el-dialog{
      height: 415px;
    }
    .el-dialog__body{
      padding: 10px 40px;
      height: 300px;
      overflow: auto;
    }
  }
  .ipt{
    width: 350px;
  }
  .pages{
    width: 90%;
    text-align: right; 
    margin-top: 20px;
  }
  .box{
    display: flex;
    align-items: center;
  }
}
</style>
